import React, { Component } from 'react'
import { NavBar, Icon } from 'antd-mobile';
import { ListContainer, ItemContainer,Burdens } from './List.style'
import { get } from 'api/http'
import { ListView } from 'antd-mobile';
import { Toast} from 'antd-mobile';

export default class List extends Component {

  constructor() {
    super();
    //起始值
    this.start = 0;
    //每页查询数据条数
    this.limit = 10;
    //查询的关键字
    this.keyword =""

    const dataSource = new ListView.DataSource({
      // getRowData,
      // getSectionHeaderData: getSectionData,
      rowHasChanged: (row1, row2) => row1 !== row2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      datalist: [],
      hasMore:true
    };

  }

  handleSearch() {
    this.start=0;
    this.setState({
      datalist:[]
    })
    this.keyword= this.refs.searchInput.value;
    this.getList()
  }

  onEndReached=()=>{
    console.log('end')
    if(!this.state.hasMore){
      Toast.info('没有更多的数据了。',1)
      return;
    }
    this.start += this.limit;
    this.getList()
  }

  render() {

    const row = (rowData, sectionID, rowID) => {
      let { img, name, burdens, all_click, favorites } = rowData;
      return (
        <ItemContainer>
          <img src={img} />
          <div className="content">
            <h2>{name}</h2>
            <Burdens>{burdens}</Burdens>
            <span>{all_click}浏览 {favorites}收藏</span>
          </div>
        </ItemContainer>
      )
    }


    return (
      <ListContainer>
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => {
            this.props.history.go(-1)
          }
          }
          rightContent={[
            <Icon key="0" type="search"
              onClick={() => this.handleSearch()}
              style={{ marginRight: '16px' }} />,
          ]}
        >
          <input ref="searchInput" ></input>
        </NavBar>
        <div className="itemContainer">
          <ListView
            ref={el => this.lv = el}
            dataSource={this.state.dataSource.cloneWithRows(this.state.datalist)}
            renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
              {this.state.isLoading ? 'Loading...' : 'Loaded'}
            </div>)}
            renderRow={row}
            style={{
              height: '100%'
            }}
            pageSize={4}
            scrollRenderAheadDistance={500}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={10}
          />


        </div>

      </ListContainer>
    )
  }


  async getList() {
    let rs = await get(`/datalist?_start=${this.start}&_limit=${this.limit}&q=${this.keyword}`)
    this.setState({
      datalist: this.state.datalist.concat(rs.data),
      hasMore:rs.data.length === this.limit,
      isLoading:false
    })
  }

  componentDidMount() {
    this.getList();
  }
}
